/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 获取全部片区下拉框
 *  */
import React, { useCallback, forwardRef, useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import { getZoneList } from '@/services/area';

const { Option } = Select;

const Index = forwardRef((props, ref) => {
  const { value, onSelect, onChange, type, ...restProps } = props;

  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);

  const filterOption = useCallback(
    (input, option) =>
      option.props.children &&
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
    [],
  );

  useEffect(
    () => {
      setLoading(true);
      getZoneList({ area_type: type }).then(zoneList => {
        setList([...zoneList]);
        setLoading(false);
      });
    },
    [type],
  );

  const handleSelect = useCallback(
    (val, options) => {
      onSelect && onSelect(val, options);
      onChange && onChange(val);
    },
    [onSelect],
  );

  return (
    <Select
      ref={ref}
      style={{ width: 250 }}
      placeholder="选择片区"
      showSearch
      filterOption={filterOption}
      value={value}
      onSelect={handleSelect}
      {...restProps}
    >
      {loading ? (
        <Option disabled value="loading">
          <Spin />
        </Option>
      ) : (
        list.map(({ site_id, site_name }) => (
          <Option key={site_id} value={site_id} name={site_name}>
            {site_name}
          </Option>
        ))
      )}
    </Select>
  );
});

export default Index;
